package Accessors;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import utils.RESTfulConnect;
import utils.URLTools;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import Callbacks.AbstractCallback;
import Enums.RFAT;
import Models.FGI;
import Models.FGIList;
import Presenter.FGIListPresenter;
import Presenter.FGIPresenter;

@SuppressWarnings("rawtypes")
public class FGIAccessor extends AbstractAccessor<FGI,FGIPresenter,AbstractCallback> {
	private final String NAME = "finishedgoodsinventory";
	private final String DIALOG = "FGI(s)";
	
	private final static FGIPresenter presenter = new FGIPresenter();
	
	AbstractCallback callback;
	
	//Modal dialog variable.
	ProgressDialog modalDialog = null;
	
	public FGIAccessor(AbstractCallback callback){
		super(presenter, callback);
		this.callback = callback;
	}
	
	//Public access functions.
	public void getAllItems(final Context context){
		String dialog = "Loading " + DIALOG + " List...";
		String rfString = NAME;
		super.getAllItems(context, dialog, rfString);
	}
	
	public void getAllInProductionItems(final Context context){
		String dialog = "Loading " + DIALOG + " List...";
		final String rfString = NAME + "/runNamedQuery/FinishedGoodsInventory.findAllInProduction";
		super.getAllItems(context, dialog, rfString);
	}
	
	public void getPackageablePerBeerID(final Context context, final int beerID){
		String dialog = "Loading " + DIALOG + " List...";
		final String rfString = NAME + "/getPackageableFGIs/" + Integer.toString(beerID);
		super.getAllItems(context, dialog, rfString);
	}
	
	public void getItem(final int id, final Context context){
		String dialog = "Loading " + DIALOG + "...";
		String rfString = NAME + "/" + Integer.toString(id);
		super.getItem(context, dialog, rfString);
	}
	
	public void doItemUpdate(final FGI item, final Context context){
		String dialog = "Updating " + DIALOG + "...";
		String rfString = NAME;
		super.doItemUpdate(item, context, dialog, rfString);
	}
	
	public void doItemInsert(final FGI item, final Context context){
		String dialog = "Inserting " + DIALOG + "...";
		String rfString = NAME;
		super.doItemInsert(item, context, dialog, rfString);
	}
	
	//Non standardized code
	public void doFGIListCreate(final FGIList fgiList, final Context context){
		modalDialog = ProgressDialog.show(context, null, "Processing FGI List Insertion...");
		final String strStart = URLTools.getURLString(context);
		final String str = NAME + "/insertFGIList";
		FGIListPresenter presenter = new FGIListPresenter();
		new UpdateFGIListTask().execute(strStart+str, URLTools.getUSERString(context), URLTools.getPASSString(context), presenter.createJSON(fgiList).toString());
	}
	
	private class UpdateFGIListTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {
            try {
                return RESTfulConnect.postResource(urls[0], urls[1], urls[2], urls[3]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@SuppressWarnings("unchecked")
		@Override
        protected void onPostExecute(String result) {
    		try{
	    		modalDialog.dismiss();
	    		FGIListPresenter fgiPresenter = new FGIListPresenter();
	    		ArrayList<FGI> items = new ArrayList<FGI>();
	    		if(result.subSequence(0, 2).equals("<?")){
	    			FGIList t = fgiPresenter.tryJSONParse(result);
		    		callback.callback(t, RFAT.INSERT, items);
	    		} else {
	    			JSONObject json = new JSONObject(result);
	    			FGIList t = fgiPresenter.createItemFromJSONObject(json);
		    		callback.callback(t, RFAT.INSERT, items);
	    		}
    		} catch(JSONException ex){
    			ex.printStackTrace();
    		} 
        }
    }
	
	public void doFGIBottleAddition(final FGI fgi, final Context context, final int qty
			, final int batchid, final int employeeid, final Date date){
		String dialog = "Inserting " + DIALOG + "...";
		modalDialog = ProgressDialog.show(context, null, dialog);
		String rfString = NAME + "/processFGIBottleAddition/" + Integer.toString(fgi.getFgiID()) 
	            + "/" + Integer.toString(qty) + "/" + Integer.toString(batchid) 
	            + "/" + Integer.toString(employeeid) + "/" + date.toString();
		rfString = rfString.replaceAll(" ", "%20");
		final String strStart = URLTools.getURLString(context);
		new UpdateItemTask().execute(strStart+rfString, URLTools.getUSERString(context), URLTools.getPASSString(context));
	}
	
	private class UpdateItemTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {
            try {
                return RESTfulConnect.putResourceNoJSON(urls[0], urls[1], urls[2]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@SuppressWarnings("unchecked")
		@Override
        protected void onPostExecute(String result) {
    		modalDialog.dismiss();
    		ArrayList<FGI> items = new ArrayList<FGI>();
    		FGI t = (FGI)presenter.getEmptyEntity();
    		callback.callback(t, RFAT.INSERT, items);
        }
    }
	
	public void doFGIBarrelAddition(final FGI fgi, final Context context, final int qty
			, final int bcsid, final int employeeid, final Date date){
		String dialog = "Inserting " + DIALOG + "...";
		modalDialog = ProgressDialog.show(context, null, dialog);
		String rfString = NAME + "/processBarrelFGIAddition/" + Integer.toString(fgi.getFgiID()) 
                + "/" + Integer.toString(qty) + "/" + Integer.toString(bcsid) 
                + "/" + Integer.toString(employeeid);
		rfString = rfString.replaceAll(" ", "%20");
		final String strStart = URLTools.getURLString(context);
		new UpdateItemTask().execute(strStart+rfString, URLTools.getUSERString(context), URLTools.getPASSString(context));
	}
}
